﻿using System;
using System.Collections.Generic;
using System.Net;
using System.Threading.Tasks;
using DevelopTool.Common.Properties;
using DevelopTool.Model.Enums;
using Sunny.UI;

namespace DevelopTool.Common
{
    /// <summary>
    /// 飞书 自定义机器人 推送消息
    /// https://open.feishu.cn/document/client-docs/bot-v3/add-custom-bot
    /// https://open.feishu.cn/document/uAjLw4CM/ukzMukzMukzM/feishu-cards/feishu-card-cardkit/feishu-cardkit-overview
    /// </summary>
    public static class FeiShuMsgHelper
    {
        /// <summary>
        /// 发送简单消息
        /// </summary>
        /// <param name="hookAddress"></param>
        /// <param name="text"></param>
        public static void SendSimpleMsg(string text)
        {
            if (string.IsNullOrEmpty(Setting.System.FeiShuMsgHookAddress)) return;
            if (string.IsNullOrEmpty(text)) return;

            //异步发送消息
            Task.Factory.StartNew(() =>
            {
                try
                {
                    //消息模板
                    string simpleMsgTemplate = Resource.FeiShuSimpleMsgTemplate;

                    //消息内容
                    simpleMsgTemplate = simpleMsgTemplate.Replace("t_text", text);

                    //发送请求
                    HttpHelper httpHelper = new HttpHelper();
                    HttpItem item = new HttpItem()
                    {
                        URL = Setting.System.FeiShuMsgHookAddress,
                        Method = "POST",
                        Postdata = simpleMsgTemplate,
                        PostEncoding = System.Text.Encoding.UTF8,
                        Timeout = 20000,//20秒超时
                    };
                    HttpResult result = httpHelper.GetData(item);
                    ResponseModel resModel = JsonHelper.DeserializeObject<ResponseModel>(result.Data);
                    if (resModel.code != 0)
                    {
                        LogHelper.WriteErrLog("发送飞书消息出错：" + resModel.msg, false);
                    }
                }
                catch (Exception ex)
                {
                    LogHelper.WriteErrLog(ex, false);
                }
            });
        }


        /// <summary>
        /// 发送卡片消息
        /// </summary>
        /// <param name="title">标题</param>
        /// <param name="content">内容</param>
        /// <param name="msgLevel">消息级别</param>
        /// <param name="isAttachedDeviceInfo">是否附带设备信息</param>
        /// <param name="time">时间</param>
        public static Tuple<bool, string> SendCardMsg(string content, string title = "", LogType msgType = LogType.Info, string contentType = "Text", DateTime? time = null)
        {
            if (string.IsNullOrEmpty(Setting.System.FeiShuMsgHookAddress)) return new Tuple<bool, string>(false, "Hook地址为空");
            if (string.IsNullOrEmpty(title) && string.IsNullOrEmpty(content)) return new Tuple<bool, string>(false, "至少需要标题或内容");

            string t_time = time == null ? DateTime.Now.DateTimeString() : ((DateTime)time).DateTimeString();//时间

            string wanIp = IpHelper.GetWANIPv4Address();//获取公网ip地址
            List<string> lanIpList = IpHelper.GetLANIPv4AddressList();//获取局域网ip地址

            string resResult = "推送失败";

            for (int i = 0; i < 2; i++)//尝试发送两次，偶尔第一次会发送失败，不知道为啥
            {
                try
                {
                    //消息模板
                    string cardMsgTemplate = Resource.FeiShuCardMsgTemplate;

                    //默认标题
                    string defaultTitle = "消息";
                    switch (msgType)
                    {
                        case LogType.Info: defaultTitle = "消息"; break;
                        case LogType.Warning: defaultTitle = "警告"; break;
                        case LogType.Error: defaultTitle = "错误"; break;
                    }

                    //标题
                    string t_title = string.IsNullOrEmpty(title) ? $"{defaultTitle}" : title;
                    cardMsgTemplate = cardMsgTemplate.Replace("t_title", t_title);

                    //标题颜色
                    string t_color = "green";
                    switch (msgType)
                    {
                        case LogType.Info: t_color = "green"; break;
                        case LogType.Warning: t_color = "orange"; break;
                        case LogType.Error: t_color = "red"; break;
                    }
                    cardMsgTemplate = cardMsgTemplate.Replace("t_color", t_color);

                    //标题图标
                    string t_icon = "succeed_filled";
                    switch (msgType)
                    {
                        case LogType.Info: t_icon = "succeed_filled"; break;
                        case LogType.Warning: t_icon = "warning_filled"; break;
                        case LogType.Error: t_icon = "error_filled"; break;
                    }
                    cardMsgTemplate = cardMsgTemplate.Replace("t_icon", t_icon);

                    //内容
                    string t_content = string.Empty;
                    if (string.IsNullOrEmpty(content))
                    {
                        cardMsgTemplate = cardMsgTemplate.Replace("t_content_text", string.Empty);
                        cardMsgTemplate = cardMsgTemplate.Replace("t_content_markdown", string.Empty);
                    }
                    else
                    {
                        content = content.Replace("\r\n", "@n@").Replace("\n\r", "@n@").Replace("\n", "@n@").Replace("\r", "@n@").Replace("@n@", "\\n");
                        content = content.Replace("\"", "\\\"");//转义" 
                        content = content.Replace((char)0x3000, ' ');//全角空格转半角空格
                        content = content.Replace("\t", "\\t");//转义\t

                        if (string.IsNullOrEmpty(contentType) || contentType == "Text")
                        {
                            t_content = content;
                            cardMsgTemplate = cardMsgTemplate.Replace("t_content_text", t_content);
                            cardMsgTemplate = cardMsgTemplate.Replace("t_content_markdown", string.Empty);
                        }
                        else
                        {
                            t_content = $"```{contentType}\\n{content}";//Markdown代码块
                            cardMsgTemplate = cardMsgTemplate.Replace("t_content_markdown", t_content);
                            cardMsgTemplate = cardMsgTemplate.Replace("t_content_text", string.Empty);
                        }
                    }


                    //备注（设备信息）
                    string computerName = System.Environment.MachineName;//获取计算机名称
                    string userName = System.Environment.UserName;//获取当前系统用户名称                                        
                    string systemOsName = WindowsHelper.GetSystemOsName();//获取系统版本                        
                    string t_appName = GlobalData.AppName_zh + " V" + System.Windows.Forms.Application.ProductVersion.ToString();//应用名称
                    string t_deviceInfo = $"系统版本：{systemOsName}\\n系统名称：{computerName}\\n系统用户名：{userName}\\n内网IP：{string.Join("\\t", lanIpList)}\\n公网IP：{wanIp}\\n时间：{t_time}\\n[{t_appName}]";

                    cardMsgTemplate = cardMsgTemplate.Replace("t_deviceInfo", t_deviceInfo);

                    //发送请求
                    HttpHelper httpHelper = new HttpHelper();
                    HttpItem item = new HttpItem()
                    {
                        URL = Setting.System.FeiShuMsgHookAddress,
                        Method = "POST",
                        Postdata = cardMsgTemplate,
                        PostEncoding = System.Text.Encoding.UTF8,
                        Timeout = 20000,//20秒超时
                    };
                    HttpResult result = httpHelper.GetData(item);

                    if (result.StatusCode != HttpStatusCode.OK)
                    {
                        resResult = result.Data;
                        continue;
                    }
                    else
                    {
                        ResponseModel resModel = JsonHelper.DeserializeObject<ResponseModel>(result.Data);
                        if (resModel.code == 0)
                        {
                            return new Tuple<bool, string>(true, "推送成功");
                        }
                        else
                        {
                            resResult = "发送飞书消息失败：" + resModel.msg;
                            LogHelper.WriteErrLog(resResult, false);
                            contentType = "Text";
                            continue;//若第一次发送失败就再来一次
                        }
                    }
                }
                catch (Exception ex)
                {
                    LogHelper.WriteErrLog(ex, false);
                    resResult = ex.Message;
                    continue;
                }
            }
            return new Tuple<bool, string>(false, resResult);
        }


        /// <summary>
        /// 异步发送卡片消息
        /// </summary>
        /// <param name="title">标题</param>
        /// <param name="content">内容</param>
        /// <param name="msgLevel">消息级别</param>
        /// <param name="isAttachedDeviceInfo">是否附带设备信息</param>
        /// <param name="time">时间</param>
        public static void SendCardMsgAsync(string content, string title = "", LogType msgType = LogType.Info, string contentType = "Text", DateTime? time = null)
        {
            //异步发送消息
            _ = Task.Factory.StartNew(() =>
            {
                SendCardMsg(content, title, msgType, contentType, time);
            });
        }
    }

    /// <summary>
    /// 响应消息实体
    /// </summary>
    public class ResponseModel
    {
        /// <summary>
        /// 响应状态，0=成功，其它=失败
        /// </summary>
        public int code { get; set; }

        /// <summary>
        /// 响应消息
        /// </summary>
        public string msg { get; set; }
    }

}
